package com.zhang.service.aop;

import com.myspring.springaop.MethodInvocation;
import com.myspring.springaop.advice.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

// 定义拦截器拦截器，proxyFactory创建时，通过构造函数加载
public class LogInterceptor implements MethodInterceptor {

    // 拦截器实现，CGLIB代理方式 MethodInterceptor.intercept()
    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        Object result = null;
        if(method.getName().equals("add")){
            System.out.println("[CGLIB] Before method: " + method.getName());
            result = proxy.invokeSuper(obj, args);
            System.out.println("[CGLIB] After method: " + method.getName());

        }
        return result;

    }


    // 拦截器实现，JDK代理方式  InvocationHandler.invoke()
    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        System.out.println("JDK代理方式---Before method: " + invocation.getMethod().getName());
        Object result = invocation.proceed();
        System.out.println("JDK代理方式---After method: " + invocation.getMethod().getName());
        return result;
    }
}